package com.prtek.reminder.util;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {

  public static String getAppid(File uuidFile) {
    String sdcardId = null;
    try {
      BufferedReader br = new BufferedReader(new FileReader(uuidFile));
      sdcardId = br.readLine();
      br.close();
    } catch (Exception e) {
      Log.e("reminder", "FileUtil", e);
    }
    return sdcardId == null ? "" : sdcardId;
  }

  public static String getMountedDirs() {

    final List<File> mountedDirs = new ArrayList<File>();
    final File[] topDirs = new File("/mnt").listFiles();
    for (File topDir : topDirs) {
      if (!topDir.isDirectory()) {
        continue;
      }
      if (topDir.canWrite()) {
        mountedDirs.add(topDir);
      } else {
        final File[] dirs = topDir.listFiles();
        if (dirs != null) {
          for (File dir : dirs) {
            if (dir.isDirectory() && dir.canWrite()) {
              mountedDirs.add(dir);
            }
          }
        }
      }
    }

    return mountedDirs.isEmpty() ? "" : mountedDirs.get(0).getPath();
  }

  public static String getAppCacheDir(Context context) {
    String storageRootPath = null;
    try {
      if (context.getExternalCacheDir() != null) {
        storageRootPath = context.getExternalFilesDir("").getCanonicalPath();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    if (TextUtils.isEmpty(storageRootPath)) {
      storageRootPath = Environment.getExternalStorageDirectory() + "/" + context.getPackageName();
    }

    return storageRootPath;
  }

  public static byte[] readFile(File file) {
    FileInputStream fis = null;
    byte[] bytes = null;
    try {
      fis = new FileInputStream(file);
      bytes = new byte[fis.available()];
      fis.read(bytes);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
    return bytes;
  }

  public static void deleteFile(String wavFile) {
    if (TextUtils.isEmpty(wavFile)) {
      return;
    }
    File file =new File(wavFile);
    if (file.exists()) {
      file.delete();
    }
  }
}
